import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Stack;

public class p2 {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(7);
        l1.next = new ListNode(8);
        l1.next.next = new ListNode(9);
        ListNode l2 = new ListNode(7);
        l2.next = new ListNode(8);
        ListNode ans = new p2().addTwoNumbers(l1,l2);
        while (ans != null){
            System.out.println(ans.val);
            ans = ans.next;
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode ans = new ListNode(0);
        ListNode now = ans;
        int carry = 0;
        while (l1 != null || l2 != null){
            if(l1 == null){
                now.next = new ListNode((l2.val + carry) % 10);
                now = now.next;
                carry = (l2.val + carry) / 10;
                l2 = l2.next;
            }else if(l2 == null){
                now.next = new ListNode((l1.val + carry) % 10);
                now = now.next;
                carry = (l1.val + carry) / 10;
                l1 = l1.next;
            }else{
                now.next = new ListNode((l1.val + l2.val + carry) % 10);
                now = now.next;
                carry = (l1.val + l2.val + carry) / 10;
                l1 = l1.next;
                l2 = l2.next;
            }
        }
        if(carry != 0){
            now.next = new ListNode(carry);
        }
        return ans.next;
    }
}
